var I = 'fillStyle',
  J = 'fillRect',
  K = '#e96900',
  c = document.getElementById('c'),
  C = c.getContext('2d'),
  w = h = 20,
  W = c.width,
  H = c.height,
  M = W / w,
  N = H / h,
  V = parseInt,
  R = Math.random,
  T = setTimeout,
  D = {97: {x: -1, y: 0}, 115: {x: 0, y: 1}, 100: {x: 1, y: 0}, 119: {x: 0, y: -1}},
  B = [{x: V(w / 2), y: h, d: 119}],
  f = X();
onkeypress = function (e) {
  if (D[e.which]) B[0].d = e.which;
};
C.m = function (f, a) {
  return C[f].apply(C, a), C;
};
C.s = function (f, v) {
  return C[f] = v, C;
};
function P (p, a, b, c) {
  C.s('strokeStyle', '#fff').m('strokeRect', [p.x * M, p.y * N, M, N]).s(I, c || '#aaa').m(J, [p.x * M, p.y * N, M, N]);
}
function X () {
  var p = {x: V(R() * w), y: V(R() * h)};
  return B.some(s) ? X() : p;
}
function o () {
  C.s(I, K).s('font', 'bold 24px 宋体').m('fillText', ['游戏结束', (W - 24 * 4) / 2, (H - 24) / 2]);
}
function n (p) {
  var d = D[p.d];
  return {x: p.x + d.x, y: p.y + d.y, d: p.d};
}
function s (a, b) {
  return a.x == b.x && a.y == b.y;
}
function g () {
  var a = n(B[0]), L = B.length, i = 0;
  if (!(a.x >= 0 && a.x < w && a.y >= 0 && a.y < h))
    return o();
  while (i < L)
    if (s(a, B[i++]))
      return o();
  B.unshift(a);
  (f.x == a.x && f.y == a.y) ? f = X() : B.pop();
  C.s(I, '#f1fedd').m(J, [0, 0, W, H]);
  P(f, 0, 0, K);
  P(B[0], 0, 0, '#2d64b3');
  B.slice(1).forEach(P);
  T(g, 200 - L * 1.5);
}
g();